<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of user_obj
 *
 * @author Juraj
 */
class user_obj {

    public function login($login, $password) {

        $db_obj = new db_obj();

        $user = $db_obj->getRow("SELECT users_id AS user_id, userlevel AS user_type_id FROM " . $GLOBALS['tb_users'] . " WHERE active=1 AND login='" . strip_tags(htmlspecialchars($login)) . "' AND password='" . strip_tags(htmlspecialchars(md5($password))) . "'");

        return $user;
    }

    public function getUserArea($user_type_id) {
        $user_type_id = (int) $user_type_id;
        if ($user_type_id < 0)
            return new error_obj('empty $user_type_id', get_class(), __FUNCTION__);

        $db_obj = new db_obj();
        return $db_obj->getOne("SELECT id FROM " . $GLOBALS['tb_user_areas'] . " WHERE '" . $user_type_id . "' BETWEEN min AND max");
    }

    public function logout() {
        session_unset();
        session_destroy();
    }

    public function getUsers($what = "*", $filter = array(), $order = array(), $limit = '') {

        $db_obj = new db_obj();

        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)){
            if (!empty($order['table'])){
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' .  $order['orderBy'] . ' ' . $order['order'];
                $connector = 'AND ' . $GLOBALS['tb_users'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'];
            }
        }
        if ($limit != '')
            $limit = ' LIMIT ' . $limit;
        if (strpos($what, 'COUNT') === false){
            $what = $GLOBALS['tb_users'] . '.' . $what;
        }        

        $where = 'WHERE 1=1';

        foreach ($filter as $key => $value) {
            if ($key == 'clients') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= "client='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } elseif ($key == 'levels') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= "userlevel='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } else {
                $where .= " AND " . $key . "='" . $value . "'";
            }
        }

        $sql = "SELECT $what FROM " . $GLOBALS['tb_users'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug("getAllUsers sql", $sql);


        return $db_obj->getAll($sql);
    }
    
    public function getUsersByFulltext($fulltext, $filter = array(), $order = array(), $limit = '', $what = '*') {
        $where = '';
        $db_obj = new db_obj();
        
        $other_table = '';
        $other_string = '';
        $connector = '';
        if (!empty($order)){
            if (!empty($order['table'])){
                $other_table = ', ' . $order['table'];
                $other_string = "ORDER BY " . $order['table'] . '.' .  $order['orderBy'] . ' ' . $order['order'];
                $connector = 'AND ' . $GLOBALS['tb_users'] . '.' . $order['connector'];
            } else {
                $other_string = "ORDER BY " . $order['orderBy'] . ' ' . $order['order'];
            }
        }

        if (!empty($fulltext)) {
            $fulltext = strip_tags(trim($fulltext));

            $fulltext = explode(" ", $fulltext);
            $fulltextResults = array();
            foreach ($fulltext as $key => $word) {
                $sql = "SELECT " . $GLOBALS['tb_users'] . ".users_id 
                    FROM " . $GLOBALS['tb_users'] . ",
                         " . $GLOBALS['tb_clients'] . ",
                         " . $GLOBALS['tb_userslevels'] . "
                    WHERE 
                    " . $GLOBALS['tb_clients'] . ".klient_id = " . $GLOBALS['tb_users'] . ".client AND
                    " . $GLOBALS['tb_userslevels'] . ".levelId = " . $GLOBALS['tb_users'] . ".userlevel AND (
                    " . $GLOBALS['tb_users'] . ".name LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".surname LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".email LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".login LIKE '%" . $word . "%' OR 
                    " . $GLOBALS['tb_users'] . ".position LIKE '%" . $word . "%' OR
                    " . $GLOBALS['tb_clients'] . ".name LIKE '%" . $word . "%' OR
                    " . $GLOBALS['tb_clients'] . ".fullName LIKE '%" . $word . "%' OR
                    " . $GLOBALS['tb_userslevels'] . ".level LIKE '%" . $word . "%'
                    )";
                
                $fulltextResults[] = array_unique($db_obj->getCol($sql));
            }
            if (isset($fulltextResults[0]) && !empty($fulltextResults[0])) {
                $temp = $fulltextResults[0];
                foreach ($fulltextResults as $key => $array) {
                    $temp = array_intersect($temp, $array);
                }
                if (!empty($temp)) {
                    $where .= 'WHERE (';
                    foreach ($temp as $id) {
                        $where .= "users_id='" . $id . "' OR ";
                    }
                    $where = substr($where, 0, $length - 4);
                    $where .= ')';
                } else {
                    $where .= 'WHERE 1=2';
                }
            } else {
                $where .= 'WHERE 1=2';
            }
        } else {
            $where .= 'WHERE 1=1';
        }

        if ($limit != '')
            $limit = ' LIMIT ' . $limit;
        if (strpos($what, 'COUNT') === false){
            $what = $GLOBALS['tb_users'] . '.' . $what;
        }

        foreach ($filter as $key => $value) {
            if ($key == 'clients') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= "client='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } elseif ($key == 'levels') {
                if (is_array($value)) {
                    $where_or .= " AND ( ";
                    foreach ($value as $k => $v) {
                        $where_or .= "userlevel='" . $v . "' OR ";
                    }
                    $where_or = substr($where_or, 0, strlen($where_or) - 4);
                    $where_or .= " )";
                    $where .= $where_or;
                }
            } else {
                $where .= " AND " . $key . "='" . $value . "'";
            }
        }
        
        
        $sql = "SELECT $what FROM " . $GLOBALS['tb_users'] . " $other_table $where $connector $other_string $limit";
        base_obj::debug('getListOfUsers sql', $sql);

        return $db_obj->getAll($sql);
    }

    public function getUserById($id, $cols = array()) {
        $id = (int) $id;
        if (empty($id))
            return new error_obj('empty user id', get_class(), __FUNCTION__);

        $what = '';
        if (!empty($cols)) {
            foreach ($cols as $value) {
                $what .= $value . ',';
            }
            $what = substr($what, 0, strlen($what) - 1);
        } else {
            $what .= '*';
        }

        $db_obj = new db_obj();
        return $db_obj->getRow("SELECT $what FROM " . $GLOBALS['tb_users'] . " WHERE users_id=$id");
    }

    function checkAdd_user($check_data) {
        $result = array();
        foreach ($check_data as $key => $value) {
            switch ($key) {
                case 'name':
                    if (empty($value))
                        $result[] = $key;
                    break;
                case 'surname':
                    if (empty($value))
                        $result[] = $key;
                    break;
                case 'login':
                    if (empty($value))
                        $result[] = $key;
                    break;
                case 'password':
                    if (empty($value))
                        $result[] = $key;
                    if (strlen(trim($value))<6)
                        $result[] = 'passwordShort';
                    break;
                case 'client':
                    if (empty($value))
                        $result[] = $key;
                    break;
                case 'userlevel':
                    if (empty($value))
                        $result[] = $key;
                    break;
                case 'active':
                    if ($value != 0 && $value != 1)
                        $result[] = $key;
                    break;
            }
        }
        return $result;
    }
    
    function isUniqueLogin($toCompare){
        if (empty($toCompare))
            return new error_obj('empty $toCompare', get_class(), __FUNCTION__);

        $db_obj = new db_obj();
        $res = $db_obj->getOne("SELECT users_id FROM " . $GLOBALS['tb_users'] . " WHERE login='".  strip_tags($toCompare) ."'");
        
        if (error_obj::isError($res))
            return false;
        elseif (empty($res)) 
            return true;
        else 
            return false;
    }
    
    public function addUser($in_data) {
        if (empty($in_data)) {
            return new error_obj('addUser -> empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $result = $db_obj->insert($GLOBALS['tb_users'], $in_data);
        if (error_obj::isError($result))
            return $result;
        else
            return $db_obj->lastInsertedId();
    }
    
    public function deleteUserById($id) {
        $id = (int) $id;
        if (empty($id)){
            return new error_obj('deleteUser -> empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        
        $sql = "DELETE FROM " . $GLOBALS['tb_users'] . " WHERE users_id='".$id."'";
        
        $result = $db_obj->query($sql);
        return $result;
    }
    
    public function editUser($in_data, $id) {
        $id = (int) $id;
        if (empty($id)) {
            return new error_obj('empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        $keys = array('users_id' => $id);
        return $db_obj->update($GLOBALS['tb_users'], $in_data, $keys);
    }
    
    public function addAssociatedClient($in_data) {
        if (empty($in_data)) {
            return new error_obj('empty $in_data', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        return $db_obj->insert($GLOBALS['tb_ref_user_clients'], $in_data);
    }
    
    public function getAssociatedClientsByUserId($user_id) {
        $id = (int) $user_id;
        if (empty($id))
            return new error_obj('empty user id', get_class(), __FUNCTION__);

        $db_obj = new db_obj();
        return $db_obj->getCol("SELECT client_id FROM " . $GLOBALS['tb_ref_user_clients'] . " WHERE user_id=$id");
    }
    
    public function deleteAssociatedClientsByUserId($user_id){
        $id = (int) $user_id;
        if (empty($id)){
            return new error_obj('empty $id', get_class(), __FUNCTION__);
        }
        $db_obj = new db_obj();
        
        $sql = "DELETE FROM " . $GLOBALS['tb_ref_user_clients'] . " WHERE user_id='".$id."'";
        
        $result = $db_obj->query($sql);
        return $result;
    }
    
    public function visibleUser($id) {
        if ($_SESSION['user']['profile']['userlevel'] != USER_TYPE_CLIENT)
            return true;
        
        $id = (int) $id;
        if (empty ($id))
            return false;
        
        $user = $this->getUserById($id);
        
        if ($user['userlevel']!=USER_TYPE_CLIENT)
            return false;
        
        if (isset($_SESSION['user']['clients'][$user['client']]) && !empty($_SESSION['user']['clients'][$user['client']]))
            return true;
        
        return false;
    }
    
    public function setUserOptions($in_options) {
        if (empty($in_options))
            return new error_obj('empty $in_options', get_class(), __FUNCTION__);
        
        $db_obj = new db_obj();
        $keys = array('userId' => $in_options['userId']);
        $result = $db_obj->insertUpdate($GLOBALS['tb_user_options'], $in_options, $keys);
        return $result;
    }
    
    public function getUserOptions($in_user_id){
        $id = (int) $in_user_id;
        if (empty($id))
            return new error_obj('empty $id', get_class(), __FUNCTION__);
        
        $sql = "SELECT * FROM " .$GLOBALS['tb_user_options']. " WHERE userId='$id'";
        $db_obj = new db_obj();
        return $db_obj->getRow($sql);
    }
    
    public function isAssignedClientToTechnic($userId){
        $userId = (int) $userId;
        if (empty($userId))
            return new error_obj('empty $userId', get_class(), __FUNCTION__);
        
        $db_obj = new db_obj();
        
        $sql = "SELECT klient_id FROM " . $GLOBALS['tb_clients'] . " WHERE contactPerson = '".$_SESSION['user']['user_id']."'";
        $clients = $db_obj->getCol($sql);
        if (error_obj::isError($clients))
            return $clients;
        
        if (!empty($clients)){
            $where = "userlevel='".USER_TYPE_CLIENT."' AND users_id = '".$userId."' AND (" ;
            foreach ($clients as $id) {
                $where .= "client = '".$id."' OR ";
            }
            $where = substr($where, 0, strlen($where) - 4);
            $where .= ")";
            $sql = "SELECT users_id FROM " . $GLOBALS['tb_users'] . " WHERE $where";
            $is = $db_obj->getOne($sql);
            
            if (error_obj::isError($is))
                return $is;
            
            if (empty($is))
                return false;
            
            return $is;
            
        } else {
            return false;
        }
    }
    
    public static function smarty_isAssignedClientToTechnic($params){
        $userId = (int) $params['userId'];
        if (empty($userId))
            return -1;
        
        $isAssigned = user_obj::isAssignedClientToTechnic($userId);
        
        if (error_obj::isError($isAssigned) || !$isAssigned)
            return -1;
        
        return $isAssigned;
    }

}

?>
